<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// 应用公共文件




/**
 * 操作成功
 *
 * @param string  $msg
 * @param integer $code
 */
function msg(string $msg = "", int $code = 0)
{
    throw new \Exception($msg, $code);
}

/**
 * 返回错误信息
 *
 * @param string  $msg
 * @param integer $code
 */
function fault(string $msg = "", int $code = 1)
{
    throw new \Exception($msg, $code);
}





/**
 * 获取分页参数
 * @example page(...page())
 */
function page()
{
    return [input('get.page/d', 1), input('get.limit/d', 10)];
}

/**

 * $msg 待提示的消息

 * $url 待跳转的链接

 * $icon 这里主要有两个，5和6，代表两种表情（哭和笑）

 * $time 弹出维持时间（单位秒）

 */


function alert($msg='',$url='',$icon='',$time=3){

    $str='<meta name="viewport" content="initial-scale=1, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta http-equiv="Access-Control-Allow-Origin" content="*" />
    <meta http-equiv="pragma" content="no-cache" />
    <script type="text/javascript" src="/static/index/js/jquery-3.4.1.min.js"></script><script type="text/javascript" src="/static/index/layer/2.4/layer.js"></script>';//加载jquery和layer

    $str.='<script>$(function(){layer.msg("'.$msg.'",{icon:'.$icon.',time:'.($time*1000).'});setTimeout(function(){self.location.href="'.$url.'"},2000)});</script>';//主要方法
    return $str;
}



//删除目录及文件，传入目录
function delFileByDir($dir) {
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {

            $fullpath = $dir . "/" . $file;
            if (is_dir($fullpath)) {
                delFileByDir($fullpath);
            } else {
                unlink($fullpath);
            }
        }
    }
    closedir($dh);
}




function request_post($url, $data = array())
{
    $timeout = 100;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($ch);
    if (false === $result) {
        $result = curl_errno($ch);
    }
    curl_close($ch);
    return $result;
}


function request_file($url, $data = array())
{
    $fields['file'] = new CURLFile(realpath($_FILES['file']['tmp_name']));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); //连接超时
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

    $result = curl_exec($ch);
    $info = curl_getinfo($ch);
    if (false === $result) {
        $result = curl_errno($ch);
    }
    curl_close($ch);
    return $result;
}

/**
 * @param string $url get请求地址
 * @param int $httpCode 返回状态码
 * @return mixed
 */
function curl_get($url, &$httpCode = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}

/**
 * 计算两个经纬度相差的距离
 * @param $lng1
 * @param $lat1
 * @param $lng2
 * @param $lat2
 * @return float|int
 */
function addresstoweidu($lng1, $lat1, $lng2, $lat2)
{
    $lng1 = 118.88812984364158;  //经度1
    $lat1 = 31.947418655302248;   //纬度1
    $lng2 = 118.88782102099347;  //经度2
    $lat2 = 31.947298390448976;   //纬度2
    $EARTH_RADIUS = 6378137;   //地球半径
    $RAD = pi() / 180.0;
    $radLat1 = $lat1 * $RAD;
    $radLat2 = $lat2 * $RAD;
    $a = $radLat1 - $radLat2;    // 两点纬度差
    $b = ($lng1 - $lng2) * $RAD;  // 两点经度差
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 10000) / 10000;
    return $s;
}


/**
 * @return 随机qrcode字符
 */
function makeOrderNo()
{
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn =
        $yCode[intval(date('Y')) - 2020] . strtoupper(dechex(date('m'))) . date(
            'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
            '%02d', rand(0, 99));
    return $orderSn;
}


function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0;
         $i < $length;
         $i++) {
        $str .= $strPol[rand(0, $max)];
    }

    return $str;
}

function getRanderstr()
{
    $code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    return $code[intval(date('Y')) - 2020] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
}

function print_json($ret = 0, $msg = 'ok', $data = array())
{

    $output_params = array('code' => $ret, 'msg' => $msg, 'data' => $data);
    $output_json_text = json_encode($output_params, JSON_NUMERIC_CHECK);
    header('Content-type: application/json;charset=utf-8');
    echo $output_json_text;
    exit(0);
}

function p_json($ret = 0, $msg = 'ok', $data = array())
{

    $output_params = array('code' => $ret, 'message' => $msg, 'result' => $data);
    $output_json_text = json_encode($output_params, JSON_NUMERIC_CHECK);
    header('Content-type: application/json;charset=utf-8');
    echo $output_json_text;
    exit(0);
}

/**
 * 数组按键名排序
 * @param $arrays
 * @param $sort_key
 * @param int $sort_order
 * @param int $sort_type
 * @return bool
 */
function my_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
{
    if (is_array($arrays)) {
        foreach ($arrays as $array) {
            if (is_array($array)) {
                $key_arrays[] = $array[$sort_key];
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
    array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
    return $arrays;
}


/**
 * 取标题头字母
 * @param $str
 * @return string|null
 */
function getFirstCharter($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) return 'A';
    if ($asc >= -20283 && $asc <= -19776) return 'B';
    if ($asc >= -19775 && $asc <= -19219) return 'C';
    if ($asc >= -19218 && $asc <= -18711) return 'D';
    if ($asc >= -18710 && $asc <= -18527) return 'E';
    if ($asc >= -18526 && $asc <= -18240) return 'F';
    if ($asc >= -18239 && $asc <= -17923) return 'G';
    if ($asc >= -17922 && $asc <= -17418) return 'H';
    if ($asc >= -17417 && $asc <= -16475) return 'J';
    if ($asc >= -16474 && $asc <= -16213) return 'K';
    if ($asc >= -16212 && $asc <= -15641) return 'L';
    if ($asc >= -15640 && $asc <= -15166) return 'M';
    if ($asc >= -15165 && $asc <= -14923) return 'N';
    if ($asc >= -14922 && $asc <= -14915) return 'O';
    if ($asc >= -14914 && $asc <= -14631) return 'P';
    if ($asc >= -14630 && $asc <= -14150) return 'Q';
    if ($asc >= -14149 && $asc <= -14091) return 'R';
    if ($asc >= -14090 && $asc <= -13319) return 'S';
    if ($asc >= -13318 && $asc <= -12839) return 'T';
    if ($asc >= -12838 && $asc <= -12557) return 'W';
    if ($asc >= -12556 && $asc <= -11848) return 'X';
    if ($asc >= -11847 && $asc <= -11056) return 'Y';
    if ($asc >= -11055 && $asc <= -10247) return 'Z';
    return null;
}

function getFirstCharters($str = "")
{


    $so = "";
    for ($i = 0; $i < mb_strlen($str, 'utf-8'); $i++) {
        $kk = mb_substr($str, $i, $i + 1, 'utf-8');
        $so .= getFirstCharter($kk);
    }

    dump($so);
    die;

}


/**
 * 导出表格
 * @param $data
 * @param string
 *
 *
 */
function create_xls($data, $filename = 'simple.xls')
{
    ini_set('max_execution_time', '0');
    Vendor('PHPExcel.PHPExcel');
    $filename = str_replace('.xls', '', $filename) . '.xls';
    $phpexcel = new \PHPExcel();
    $phpexcel->getProperties()
        ->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");
    $phpexcel->getActiveSheet()->fromArray($data);
    $phpexcel->getActiveSheet()->setTitle('Sheet1');
    $phpexcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$filename");
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0
    $objwriter = \PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
    $objwriter->save('php://output');
    exit;
}


function create_csv($data, $header = null, $filename = 'simple.csv')
{
    // 如果手动设置表头；则放在第一行
    if (!is_null($header)) {
        array_unshift($data, $header);
    }
    // 防止没有添加文件后缀
    $filename = str_replace('.csv', '', $filename) . '.csv';
    Header("Content-type:  application/octet-stream ");
    Header("Accept-Ranges:  bytes ");
    Header("Content-Disposition:  attachment;  filename=" . $filename);
    foreach ($data as $k => $v) {
        // 如果是二维数组；转成一维
        if (is_array($v)) {
            $v = implode(',', $v);
        }
        // 替换掉换行
        $v = preg_replace('/\s*/', '', $v);
        // 转成gbk以兼容office乱码的问题
        echo iconv('UTF-8', 'GBK', $v) . "\r\n";
    }
    exit;

}


function import_excel($file)
{
    // 判断文件是什么格式
    $type = pathinfo($file);
    $type = strtolower($type["extension"]);
    $type = $type === 'csv' ? $type : 'Excel5';
    ini_set('max_execution_time', '0');
    Vendor('PHPExcel.PHPExcel');
    // 判断使用哪种格式
    $objReader = PHPExcel_IOFactory::createReader($type);
    $objPHPExcel = $objReader->load($file);
    $sheet = $objPHPExcel->getSheet(0);
    // 取得总行数
    $highestRow = $sheet->getHighestRow();
    // 取得总列数
    $highestColumn = $sheet->getHighestColumn();
    //循环读取excel文件,读取一条,插入一条
    $data = array();
    //从第一行开始读取数据
    for ($j = 1; $j <= $highestRow; $j++) {
        //从A列读取数据
        for ($k = 'A'; $k <= $highestColumn; $k++) {
            // 读取单元格
            $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
        }
    }
    return $data;
}

function encrypt($msgu, $key = "www.tvata.com")
{
    if ($msgu != "" && $key != "") {
        $delmsg = md5($msgu);
        $rname = substr($delmsg, 5, 1) . "," . substr($delmsg, 7, 1) . "," . substr($delmsg, 15, 1) . "," . substr($delmsg, 17, 1) . "," . substr($delmsg, 29, 1);
        $rnamearray = explode(',', $rname);
        $rpass = md5($key);
        $r_msg = str_replace($rnamearray, "", $rpass);
    } else {
        $r_msg = $key;
    }
    return md5($r_msg);
}


function debugshow()
{
    \think\Db::listen(function ($sql, $time, $explain, $master) {
        // 记录SQL
        echo $sql . ' [' . $time . 's] ' . ($master ? 'master' : 'slave');
        // 查看性能分析结果
        dump($explain);
    });
}


function OssUploads($download_file = null)
{
    try {
        $ossClient = new \OSS\OssClient(config('Oss.accessKeyId'), config('Oss.accessKeySecret'), config('Oss.endpoint'));
        $png = pathinfo($download_file);
        $bucket = config('Oss.bucket');
        $object = "json/" . $png['basename'];
        $ossClient->uploadFile($bucket, $object, $download_file);
    } catch (OssException $e) {
        print_r($e->getMessage());
    }
}

function getInIp()
{
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    return $ip;
}


function encryptions($data = null, $params = null)
{
    $aes = new Security();
    return $aes->encrypt($data, $params);
}


function decryptptions($data = null, $params = null)
{
    $aes = new Security();
    return $aes->decrypt($data, $params);
}

function _isAssocArray(array $var)
{
    return array_diff_assoc(array_keys($var), range(0, sizeof($var))) ? TRUE : FALSE;
}

function trimall($str = null)
{
    $oldchar = array(" ", "　", "\t", "\n", "\r");
    $newchar = array("", "", "", "", "");
    return str_replace($oldchar, $newchar, $str);
}


function aesencrypt($key = "", $str = "")
{
    $aes = new \PhpAes\Aes($key, 'ECB');
    $y = $aes->encrypt($str);
    return base64_encode($y);
}

function aesdecrypt($key = "", $str = "")
{
    $aes = new \PhpAes\Aes($key, 'ECB');
    $y = $aes->decrypt(base64_decode($str));
    return $y;
}


function codeencrypt($data, $key)
{
    $key = md5($key);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}


function codedecrypt($data, $key)
{
    $key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $len = strlen($data);
    $l = strlen($key);
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return $str;
}

/**
 * PHP 版本post发送请求
 * @param $url
 * @param $postData
 * @return string
 */
function sendPost($url, $postData)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    $tmpInfo = curl_exec($ch);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $body = substr($tmpInfo, $headerSize);
    curl_close($ch);
    return $body;
}

/**
 * PHP 版本获得加密秘钥
 * @param $postData
 * @param $secret
 * @return string
 */
function getSign($postData, $secret)
{
    //获得当前时间戳（秒级）
    $postData['api_time_stamp'] = time();

    //获得随机数 (0-100000)
    $postData['api_random_number'] = rand(0, 100000);

    //按照键排序
    ksort($postData);

    //拼接加密字符串
    $signature = 'secret=' . $secret;
    foreach ($postData as $k => $v) {
        $signature .= '&' . $k . '=' . $v;
    }

    //返回加密字符串
    return md5(sha1($signature)) . '_' . $postData['api_time_stamp'] . '_' . $postData['api_random_number'];
}


/**
 * 获取周围坐标
 * Enter description here ...
 * @param unknown_type $lng 固定坐标经度
 * @param unknown_type $lat 固定坐标纬度
 * @param unknown_type $distance 搜索周边距离，单位KM
 * @return multitype:multitype:number
 */
function returnSquarePoint($lng, $lat, $distance = 1)
{
    $earthRadius = 6378.138; //地球半径，单位KM
    $dlng = 2 * asin(sin($distance / (2 * $earthRadius)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
    $dlat = $distance / $earthRadius;
    $dlat = rad2deg($dlat);
    return array(
        'left-top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
        'right-top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
        'left-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
        'right-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
    );

    //使用此函数计算得到结果后，带入sql查询。
//    $squares = returnSquarePoint($lng, $lat);
//    $info_sql = "select id,locateinfo,lat,lng from `lbs_info` where lat<>0 and lat>{$squares['right-bottom']['lat']} and lat<{$squares['left-top']['lat']} and lng>{$squares['left-top']['lng']} and lng<{$squares['right-bottom']['lng']} ";
}

/**
 * 计算两个坐标的直线距离
 * Enter description here ...
 * @param unknown_type $lat1
 * @param unknown_type $lng1
 * @param unknown_type $lat2
 * @param unknown_type $lng2
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6378.138; //近似地球半径千米
    // 转换为弧度
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;
    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;
    // 使用半正矢公式  用尺规来计算
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance, 2);

}

//PHP stdClass Object转array
function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

/**
 * php xml 转数组
 * @param $xml
 * @return mixed
 */
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}


//二维数组去掉重复值
function a_array_unique($array)
{
    $out = array();

    foreach ($array as $key => $value) {
        if (!in_array($value, $out)) {
            $out[$key] = $value;
        }
    }

    $out = array_values($out);
    return $out;
}

function my_array_multisort($data, $sort_order_field, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
{
    foreach ($data as $val) {
        $key_arrays[] = $val[$sort_order_field];
    }
    array_multisort($key_arrays, SORT_ASC, SORT_NUMERIC, $data);
    return $data;
}


